﻿using System;
using System.IO;
using Actya.Web.Infrastructure.ElFinderConnector.Responses;
using Actya.Web.Infrastructure.ElFinderConnector.Utils;

namespace Actya.Web.Infrastructure.ElFinderConnector.Commands
{
	public class Resize : ICommand
	{
		private readonly string _current;
		private readonly string _target;
		private readonly int _width;
		private readonly int _height;
		private readonly string _mode;
		private readonly int _x;
		private readonly int _y;

		public Resize(string current, string target, int width, int height, string mode, int x, int y)
		{
			_current = current;
			_target = target;
			_width = width;
			_height = height;
			_mode = mode;
			_x = x;
			_y = y;
		}

		public Response Execute()
		{
			var currentFolder = DirectoryUtils.GetRelativePathByHash(_current);
			var targetFilePath = DirectoryUtils.GetFilePathByHash(_target);
			var targetFileInfo = new FileInfo(targetFilePath);

			var tempFilePath = Path.Combine(Configuration.Configuration.TmbDir, Guid.NewGuid().ToString() + ".tmp");

			ImageUtils.Resize(targetFileInfo.FullName, tempFilePath, _width, _height, null, _mode, _x, _y);

			var response = new ActionCompletedResponse();

			if (File.Exists(tempFilePath))
			{
				targetFileInfo.Delete();
				File.Move(tempFilePath, targetFilePath);
				FileUtils.RemoveThumbFor(targetFilePath);
			}
			else
			{
				response.error = "Unable to resize image";
			}

			var folder = new Folder(currentFolder);
			response.cwd = folder.Cwd;
			response.cdc = folder.Contents;
			response.select = new[] {_target};
			return response;
		}
	}
}